"""
  this module provide utilities for IO, including data format conversion etc
"""
import os
import re
import glob

from task import Task

task_title_pat = re.compile(r"^(?P<task_indent>\s*)\*(?P<task_title>.*)$")
task_property_line_pat = re.compile(
    r"^(?P<task_property_indent>\s*)(\w+=[^\s=]+)(\s+\w+=[^\s=]+)*$")
task_content_line_pat = re.compile(r"^\s*[^*]?.*")

UGTD_ROOT_PATH = '/home/vincent/UGTD'
UGTD_FILE_SUFFIX = 'ugtd'

def getTask(file_obj):
    """
    return a task object from data file

    file_obj: data file object
    """
    t = None
    contents = []

    line = file_obj.readline()
    while True:
        import pdb, readline; pdb.set_trace();
        # 1. find the title line
        while line:
            m = task_title_pat.match(line)
            if not m:
                file_obj.readline()
                continue

            t = Task()
            t.setLevel(m.group('task_indent'))
            t.setTitle(m.group('task_title'))
            break
        else:
            raise Exception("Not valid data format!")

        # 2. find the optional property line
        line = file_obj.readline()
        if not line:
            yield t
            raise StopIteration
        else:
            m = task_property_line_pat.match(line)
            if m:
                properties = m.group().split()
                t.setProperties([prop.split('=') for prop in properties])
                line = file_obj.readline()

        # 3. get task contents
        if not line:
            yield t
            raise StopIteration
        else:
            contents = []
            while line:
                m = task_title_pat.match(line)
                if m:
                    t.setContent(contents)
                    yield t
                    break
                else:
                    contents.append(line)
                line = file_obj.readline()
            else:
                t.setContent(contents)
                yield t
                raise StopIteration


def getGTDFileList(initial_path):
    """
    get all gtd input files list

    initial_path -- the starting point directory
    """

    return glob.glob(os.path.join(initial_path, '*.' + UGTD_FILE_SUFFIX))

def importGTDTask(gtd_file):
    """
    create GTD task object for given GTD input file

    gtd_file -- path of a GTD input data file
    """
    data_file = file(gtd_file, 'rw')
    tasks = list(getTask(date_file))
    return tasks


